package vip.hello520.controller;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.hello520.model.ResultEnum;
import vip.hello520.model.ResultBean;
import vip.hello520.service.LoginService;
import vip.hello520.model.UserPo;

import javax.annotation.Resource;

/**
 * @author Hello
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/checkLogin.do")
    @ResponseBody
    public String checkLogin(UserPo userPo) {
        try {
            //登陆验证
            UsernamePasswordToken token = new UsernamePasswordToken(userPo.getUsername(), userPo.getPassword());
            SecurityUtils.getSubject().login(token);
        } catch (UnknownAccountException e) {
            return "用户不存在";

        } catch (AuthenticationException e) {
            return "用户名或密码错误";
        }
        return "0";
    }

    @RequestMapping(value = "/check.do")
    @ResponseBody
    public String checkName(String username) throws Exception {
        ResultBean resultBean = new ResultBean();
        if (null != username && !"".equals(username)) {
            UserPo userByName = loginService.getUserPoByName(username);
            if (null != userByName) {
                return resultFailure();
            }
        } else {
            return resultFailure();
        }
        return resultSuccess();
    }

    @RequestMapping("/reg.do")
    public String save(UserPo userPo, Model model) throws Exception {
        //参数一:加密方式
        //参数二:需要加密的字符串
        //参数三:盐
        //参数四:加密次数
        String password2Md5 = new SimpleHash("MD5", userPo.getPassword(), userPo.getUsername(), 1024).toString();
        userPo.setPassword(password2Md5);
        ResultBean resultBean = loginService.regUser(userPo);
        if (null != resultBean) {
            model.addAttribute("MSG_success", resultBean.getMessage());
            model.addAttribute("state", resultBean.getState());
            model.addAttribute("reg_name", userPo.getUsername());
            return "forward:loginAndReg/login.jsp";
        }
        return null;
    }
}
